/*
 * Copyright (c) 2012 Xilinx, Inc.  All rights reserved.
 *
 * Xilinx, Inc.
 * XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" AS A
 * COURTESY TO YOU.  BY PROVIDING THIS DESIGN, CODE, OR INFORMATION AS
 * ONE POSSIBLE   IMPLEMENTATION OF THIS FEATURE, APPLICATION OR
 * STANDARD, XILINX IS MAKING NO REPRESENTATION THAT THIS IMPLEMENTATION
 * IS FREE FROM ANY CLAIMS OF INFRINGEMENT, AND YOU ARE RESPONSIBLE
 * FOR OBTAINING ANY RIGHTS YOU MAY REQUIRE FOR YOUR IMPLEMENTATION.
 * XILINX EXPRESSLY DISCLAIMS ANY WARRANTY WHATSOEVER WITH RESPECT TO
 * THE ADEQUACY OF THE IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO
 * ANY WARRANTIES OR REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE
 * FROM CLAIMS OF INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#pragma pack(1)
#define SHARE_MEM_KEY_PATH  "/usr/lib"
#define MSG_QUEUE_KEY_PATH  "/usr/bin"
static int SHARE_MEM_KEY_ID_READ[] = {
    0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,
};
static int SHARE_MEM_KEY_ID_WRITE[] = {
    0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,
};
static int MSG_QUEUE_KEY_ID_READ[] = {
    0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,
};
static int MSG_QUEUE_KEY_ID_WRIRE[] = {
    0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,
};
struct msg{
    unsigned int len;
    unsigned char mtext[896];
};
struct msgbuf{
    long mtype;
    struct msg block;
};

int msgId, data_len;
void Get_CtrlC_handler(int sig) ;
int main()
{
	signal(SIGINT, Get_CtrlC_handler);
	struct msgbuf readbuf ;
	memset(&readbuf, 0, sizeof(readbuf));
	readbuf.mtype = 886 ;

	key_t tmp_key = ftok(MSG_QUEUE_KEY_PATH, MSG_QUEUE_KEY_ID_WRIRE[0]);
	msgId = msgget(tmp_key, IPC_CREAT|0666);
	if(msgId<0)
		printf("get queue failed\n");
	printf("msgId=%d,tmp_key=%#x\n",msgId, tmp_key);

	while(1)
	{
		data_len = msgrcv(msgId, &readbuf, sizeof(readbuf.block), readbuf.mtype, 0);
		printf("recv %d\n",data_len); //data_len == sizeof(readbuf.block)
//		for(int i=0;i<1; i++)
//		{
//			if(i%20==0) printf("\n");
//			printf("%02x ", readbuf.mtext[i]);
//		}
		printf("%02x %02d\n", readbuf.block.mtext[0], readbuf.block.len);
	}
	msgctl(msgId, IPC_RMID, NULL);
    return 0;
}

void Get_CtrlC_handler(int sig) {
	if(msgctl(msgId, IPC_RMID, 0) == -1)
	{
		 fprintf(stderr, "msgctl(IPC_RMID) failedn");
		 exit(EXIT_FAILURE);
	}
	exit(0);
}
